#include "function_pointers.h"

#include <headings.h>

#include <string.h> // for memset
#include <unistd.h> // for sleep
#include <iostream>

using namespace std;

// this defines function_pointer to be an alias name for "a pointer to
// a function that takes an int parameter an has no return value". an
// interface so to say.
typedef void (*function_pointer)(int);

// this function takes a function_pointer and an integer. it calls the
// function that function_pointer points to, passing it the parameter.
static void call(function_pointer fp, int parameter)
{
    fp(parameter);
}

// here's an implementation of this "interface" that prints out the
// value of the integer.
static void print_parameter(int parameter)
{
    cout << "          \"And the parameter is: " << parameter << "!\"\n";
}

// here's another implementation that sleeps as many seconds as the
// parameters says.
static void sleep_n(int parameter)
{
    sleep(parameter);
}

void show_function_pointers()
{
    HEADING2("Function pointers");

    cout << "  Demonstrates the usage of function pointer by defining\n";
    cout << "  a \"bare-bones\" C interface and implementing it two times.\n\n";

    cout << "  Passing print_parameter and parameter 5 ...\n";
    call(print_parameter, 2);
    cout << "  Passing sleep_n and parameter 2 ...\n";
    call(sleep_n, 2);
}
